package com.example.contextcube.util;

import android.content.Context;
import android.util.Log;

import com.example.contextcube.db.DictionaryDatabaseHelper;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 收藏管理器 - 单例模式
 * 负责管理单词收藏状态并通知观察者
 */
public class FavoriteManager {
    private static final String TAG = "FavoriteManager";
    
    private static FavoriteManager instance;
    private DictionaryDatabaseHelper dbHelper;
    private Set<String> favoritedWords = new HashSet<>();
    private List<FavoriteChangeListener> listeners = new ArrayList<>();
    private Context context;

    /**
     * 收藏状态变化监听器
     */
    public interface FavoriteChangeListener {
        void onFavoriteChanged(String word, boolean isFavorite);
    }

    private FavoriteManager() {
        // 私有构造函数
    }

    /**
     * 获取单例实例
     */
    public static synchronized FavoriteManager getInstance() {
        if (instance == null) {
            instance = new FavoriteManager();
        }
        return instance;
    }

    /**
     * 设置上下文
     */
    public void setContext(Context context) {
        this.context = context.getApplicationContext();
    }
    
    /**
     * 设置数据库助手
     */
    public void setDatabaseHelper(DictionaryDatabaseHelper dbHelper) {
        this.dbHelper = dbHelper;
        // 初始化加载所有收藏的单词
        loadAllFavorites();
    }

    /**
     * 从数据库加载所有收藏的单词
     */
    public void loadAllFavorites() {
        if (dbHelper == null) return;
        
        new Thread(() -> {
            try {
                List<String> favorites = dbHelper.getAllFavoritedWordStrings();
                
                synchronized (favoritedWords) {
                    favoritedWords.clear();
                    favoritedWords.addAll(favorites);
                }
                
                Log.d(TAG, "已加载收藏单词: " + favoritedWords.size() + "个");
                
                // 调试输出前10个收藏单词
                int count = 0;
                for (String word : favoritedWords) {
                    Log.d(TAG, "收藏单词: " + word);
                    count++;
                    if (count >= 10) break;
                }
                
            } catch (Exception e) {
                Log.e(TAG, "加载收藏单词失败", e);
            }
        }).start();
    }

    /**
     * 检查单词是否被收藏
     */
    public boolean isFavorited(String word) {
        if (word == null) return false;
        String lowercaseWord = word.toLowerCase();
        
        // 优先从内存中查询
        synchronized (favoritedWords) {
            if (favoritedWords.contains(lowercaseWord)) {
                return true;
            }
        }
        
        // 如果内存中没有，但数据库有，则更新内存
        if (dbHelper != null && dbHelper.isWordFavorited(lowercaseWord)) {
            synchronized (favoritedWords) {
                favoritedWords.add(lowercaseWord);
            }
            return true;
        }
        
        return false;
    }

    /**
     * 切换收藏状态
     */
    public boolean toggleFavorite(String word, boolean isFavorite) {
        if (word == null) {
            Log.e(TAG, "toggleFavorite失败: word为null");
            return false;
        }
        
        String lowercaseWord = word.toLowerCase();
        Log.d(TAG, "尝试" + (isFavorite ? "添加" : "移除") + "收藏: " + lowercaseWord);
        
        // 普通模式处理
        if (dbHelper == null) {
            Log.e(TAG, "toggleFavorite失败: dbHelper为null, word=" + word);
            return false;
        }
        
        // 调用数据库助手的切换收藏状态方法
        boolean success = dbHelper.toggleFavoriteWordByString(lowercaseWord, isFavorite);
        
        if (success) {
            // 更新内存中的状态
            synchronized (favoritedWords) {
                if (isFavorite) {
                    favoritedWords.add(lowercaseWord);
                } else {
                    favoritedWords.remove(lowercaseWord);
                }
            }
            
            // 通知所有监听器
            notifyListeners(lowercaseWord, isFavorite);
        } else {
            Log.e(TAG, "toggleFavorite数据库操作失败: word=" + word + ", isFavorite=" + isFavorite);
        }
        
        return success;
    }
    
    /**
     * 添加收藏状态变化监听器
     */
    public void addListener(FavoriteChangeListener listener) {
        if (listener != null && !listeners.contains(listener)) {
            listeners.add(listener);
        }
    }
    
    /**
     * 移除收藏状态变化监听器
     */
    public void removeListener(FavoriteChangeListener listener) {
        listeners.remove(listener);
    }
    
    private void notifyListeners(String word, boolean isFavorite) {
        Log.d(TAG, "通知所有监听器 (" + listeners.size() + "个): " + word + " => " + (isFavorite ? "收藏" : "取消收藏"));
        for (FavoriteChangeListener listener : new ArrayList<>(listeners)) {
            try {
                listener.onFavoriteChanged(word, isFavorite);
            } catch (Exception e) {
                Log.e(TAG, "通知监听器出错", e);
            }
        }
    }

    /**
     * 获取数据库助手
     */
    public DictionaryDatabaseHelper getDatabaseHelper() {
        return dbHelper;
    }
} 